package com.lagou.rpc.consumer.client;

import com.lagou.rpc.common.*;
import com.lagou.rpc.consumer.handler.RpcClientHandler;
import com.lagou.rpc.common.RequestMetrics;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 客户端
 * 1.连接netty服务端
 * 2.提供给调用者主动关闭资源的方法
 * 3.提供消息发送方法
 */
@Data
public class RpcClient {
    //服务端ip
    private String ip;
    //服务端端口
    private int port;
    private NioEventLoopGroup group;
    private Channel channel;
    private RpcClientHandler rpcClientHandler = new RpcClientHandler();
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public RpcClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        initClient();
    }

    /**
     * 初始化连接方法-连接netty服务端
     */
    public void initClient() {

        try {
            //1.创建线程组
            group = new NioEventLoopGroup();
            //2.创建启动助手
            Bootstrap bootstrap = new Bootstrap();
            //3.设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //添加String类型的编解码器
//                            pipeline.addLast(new StringDecoder());
//                            pipeline.addLast(new StringEncoder());
                            //添加自定义编解码器
                            pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                            pipeline.addLast(new RpcDecoder(RpcResponse.class, new JSONSerializer()));
                            //客户端handler
                            pipeline.addLast(rpcClientHandler);
                        }
                    });
            //4.连接服务端
            channel = bootstrap.connect(ip, port).sync().channel();
            // 判断连接是否有效
            if (!isValidate()) {
                close();
                return;
            }
            System.out.println("客户端初始化完成，与服务端建立连接：" + ip + ":" + port);
        } catch (Exception e) {
            e.printStackTrace();
            if (channel != null) {
                channel.close();
            }
            if (group != null) {
                group.shutdownGracefully();
            }
        }
    }


    /**
     * 提供消息发送方法
     *
     * @return
     */
    public Object send(RpcRequest requestMsg) throws ExecutionException, InterruptedException {
        System.out.println("执行调用的客户端为：" + ip + ":" + port);
        //初始化耗时对象并进行存储
        RequestMetrics.getInstance().put(ip, port, requestMsg.getRequestId());
        rpcClientHandler.setRequestMsg(requestMsg);
        Future submit = executorService.submit(rpcClientHandler);
        return submit.get();
    }

    /**
     * 判断连接是否有效
     *
     * @return
     */
    public boolean isValidate() {
        if (this.channel != null) {
            return this.channel.isActive();
        }
        return false;
    }

    /**
     * 关闭
     */
    public void close() {
        if (this.channel != null && this.channel.isActive()) {
            this.channel.close();
        }
        if (this.group != null && !this.group.isShutdown()) {
            this.group.shutdownGracefully();
        }
        System.out.println("与服务端断开：" + ip + ":" + port);
    }


}
